package com.imc.api.templmess.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/*
 * 类描述：微信Token获取工具类
 * 开发者：YT
 * 创建日期：2018/10/28 22:09
 */
@Component
public class WXTokenUtil {
    private static Logger log = LoggerFactory.getLogger(WXTokenUtil.class);
    private static AccessToken access_token = new AccessToken();

    /**
     * 获得微信 AccessToken
     * access_token是公众号的全局唯一接口调用凭据，公众号调用各接口时都需使用access_token。
     * 开发者需要access_token的有效期目前为2个小时，需定时刷新，重复获取将导致上次获取
     * 的access_token失效。
     * （此处我是把token存在Redis里面了）
     */
    public static AccessToken getWXToken(String appId, String appSecret) {
        if (null != access_token.getCurrentDate() && null != access_token.getAccessToken()) {
            if ((access_token == null || " ".equals(access_token.getAccessToken())) || (new Date().getTime() - access_token.getCurrentDate().getTime()) > 7100000) {
                String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
                JSONObject jsonObject = WXHttpsUtil.httpsRequest(tokenUrl, "GET", null);
                if (null != jsonObject) {
                    try {
                        access_token = new AccessToken();
                        access_token.setCurrentDate(new Date());
                        access_token.setAccessToken(jsonObject.getString("access_token"));
                        access_token.setExpiresin(jsonObject.getInteger("expires_in"));
                        log.error("获取token成功 " + access_token.getAccessToken());
                    } catch (JSONException e) {
                        access_token = null;
                        // 获取token失败
                        log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
                    }
                }
            }
        } else {
            String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
            JSONObject jsonObject = WXHttpsUtil.httpsRequest(tokenUrl, "GET", null);
            if (null != jsonObject) {
                try {
                    access_token = new AccessToken();
                    access_token.setCurrentDate(new Date());
                    access_token.setAccessToken(jsonObject.getString("access_token"));
                    access_token.setExpiresin(jsonObject.getInteger("expires_in"));
                    log.error("获取token成功 " + access_token.getAccessToken());
                } catch (JSONException e) {
                    access_token = null;
                    // 获取token失败
                    log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInteger("errcode"), jsonObject.getString("errmsg"));
                }
            }
        }

        return access_token;
    }
}
